<template>
	<div v-loading="loading">
		<div class="flexRBC top">
			<div class="title">{{ curSelectLabel }}</div>
			<div>
				<el-button-group>
					<el-button v-if="!$store.getters.banBtnList.includes('BTN_STAFF_ADD')" type="primary" size="medium" round @click="handleAdd">新增员工</el-button>
					<!-- <el-button
            v-if="!$store.getters.banBtnList.includes('BTN_STAFF_ADD')"
            type="primary"
            size="medium"
            round
            @click="handleQrCodeAdd"
          >二维码新增</el-button> -->
					<!-- <el-button
            v-if="!$store.getters.banBtnList.includes('BTN_STAFF_APPROVE')"
            type="primary"
            size="medium"
            round
            @click="handleApprove"
          >员工审批</el-button> -->
				</el-button-group>
			</div>
		</div>
		<!-- 搜索 -->
		<div class="list-search">
			<el-input v-model="filterForm[searchSelect]" placeholder="请输入内容" class="input-with-select" @keyup.enter.native="searchByKeyword">
				<el-select slot="prepend" v-model="searchSelect" placeholder="请选择">
					<el-option v-for="item in selectOptions" :key="item.value" :label="item.label" :value="item.value" />
				</el-select>
			</el-input>
			<el-button :loading="searchLoading" type="primary" size="medium" round icon="el-icon-search" @click="searchByKeyword">查 询</el-button>
		</div>

		<!-- 表格 -->
		<div class="table">
			<el-table :data="list" size="medium" border>
				<el-table-column prop="name" fixed="left" label="名称" />
				<!-- <el-table-column prop="username" label="账号" width="140" /> -->
				<!-- <el-table-column prop="username" label="登录账号" width="200">
					<template slot-scope="scope">
						<span>{{ scope.row.username }}@{{ userSuffix }}</span>
					</template>
				</el-table-column> -->
				<el-table-column prop="mobilePhone" label="登录账号" width="120px" />
				<!-- <el-table-column prop="wechatName" label="微信昵称" /> -->
				<el-table-column prop="shopName" label="门店">
					<template slot-scope="scope">
						<span>{{ scope.row.shopName ? scope.row.shopName : '总部' }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="roles" label="用户角色">
					<template slot-scope="scope">
						<span>{{ toRolesName(scope.row.roles) ? toRolesName(scope.row.roles) : '无' }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="roles" label="员工状态" align="center">
					<template slot-scope="scope">
						<span>{{ scope.row.status | filUserStatus }}</span>
					</template>
				</el-table-column>
				<!-- <el-table-column align="center" prop="roles" label="员工状态">
          <template slot-scope="scope">
            <span>启动</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="roles" label="分账功能">
          <template slot-scope="scope">
            <el-switch
              v-model="val"
            />
          </template>
        </el-table-column> -->
				<el-table-column label="操作" fixed="right" width="180">
					<template slot-scope="scope">
						<el-button v-if="!$store.getters.banBtnList.includes('BTN_STAFF_EDIT')" type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
						<el-button
							size="small"
							type="text"
							style="margin-right: 10px"
							@click="handleBindWx(scope.row)"
						>
							<span :class="scope.row.wechatOpenid ? 'app-text-color-info' : ''">{{ scope.row.wechatOpenid ? '解绑微信' : '绑定微信' }}</span>
						</el-button>
						<el-button v-if="!$store.getters.banBtnList.includes('BTN_STAFF_EDIT')" type="text" size="small" @click="handleDel(scope.row)">删除</el-button>
						<!-- <el-dropdown
              v-if="!$store.getters.banBtnList.includes('BTN_STAFF_CODE_RESET')||!$store.getters.banBtnList.includes('CARD_PROMOTER')||!$store.getters.banBtnList.includes('BTN_STAFF_DELETE')"
              size="small"
              @command="handleCommand($event, scope.row)"
            >
              <span class="el-dropdown-link app-text-color-primary">
                更多
                <i class="el-icon--right" />
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  :disabled="!!businessInfo.syncTmpMerchantId"
                  v-if="scope.row.id!==userId&&!$store.getters.banBtnList.includes('BTN_STAFF_CODE_RESET')"
                  command="psw"
                >重置密码</el-dropdown-item>
                <el-dropdown-item
                  v-if="!$store.getters.banBtnList.includes('CARD_PROMOTER')"
                  command="promoters"
                >推广二维码</el-dropdown-item>
                <el-dropdown-item
                  v-if="scope.row.id!==userId&&!$store.getters.banBtnList.includes('BTN_STAFF_DELETE')"
                  command="del"
                  :disabled="scope.row.syncTmpServicerId"
                >删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown> -->
					</template>
				</el-table-column>
			</el-table>
		</div>

		<!-- 分页 -->
		<pagination-direction v-if="paginationConfig.total !== 0" :config="paginationConfig" @sizeschange="sizesChange" @pagechange="pageChange" />

		<!-- 新增编辑弹框 -->
		<dialog-user ref="userDialog" :shop-id="shopId" :scope="scope" />

		<!-- 新增二维码 -->
		<dialog-user-add-qr-code ref="dialogUserAddQrCode" :shop-id="shopId" />

		<!-- 修改密码 -->
		<reset-pw ref="resetPw" :scope="scope" />

		<!-- 批量上传 -->
		<!-- <dialog-upload-excel ref="dialogUploadExcel"></dialog-upload-excel> -->

		<!-- 二维码 -->
		<dialog-user-qr-code ref="dialogUserQrCode" />

		<!-- 绑定微信 -->
		<dialog-bind-wx ref="dialogBindWx" :scope="scope" />
	</div>
</template>

<script>
import { mapGetters } from 'vuex';
import { listUser, deleteUser } from '@/api/user';
import { unBindWx } from '@/publicApi/login';
import DialogUser from './DialogUser';
import ResetPw from './ResetPw';
import DialogUserAddQrCode from './DialogUserAddQrCode';
import DialogUserQrCode from './DialogUserPromoteQrCode';
import DialogBindWx from '../../../layout/components/components/DialogBindWx.vue';

const USERSTATUS = {
	0: '禁用',
	1: '启用'
};

export default {
	components: {
		DialogUser,
		ResetPw,
		DialogUserQrCode,
		DialogUserAddQrCode,
		DialogBindWx
	},
	props: {
		shopId: {
			type: Number,
			default: null
		},
		shopName: {
			type: String,
			default: ''
		},
		curSelectLabel: {
			type: String,
			default: ''
		}
	},
	data() {
		return {
			// 配置
			statusOptions: ['停用', '正常'],
			scope: 2,
			selectOptions: [
				{
					value: 'username',
					label: '账号'
				}
			],
			searchSelect: 'username', // 搜索的类型
			// 分页配置
			paginationConfig: {
				direction: 'center', // 分页位置
				layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
				pageSizes: [10, 20], // 分页pages
				total: 0,
				page: 1, // 页数-默认1
				pageSize: 10 // 每页条数-默认10
			},
			// 状态
			loading: false,
			searchLoading: false, // 表格loading
			// 数据
			list: [],
			filterForm: {
				username: ''
			}
		};
	},
	computed: {
		...mapGetters(['userSuffix', 'userId', 'userInfo', 'businessInfo'])
	},
	filters: {
		filUserStatus(val) {
			return USERSTATUS[val] || '-';
		}
	},
	watch: {
		shopId(val) {
			this.filterForm.username = '';
			setTimeout(() => {
				this.fetchData(1);
			}, 50);
		}
	},
	mounted() {
		this.fetchData(1);
	},
	methods: {
		/**
		 * 获取数据
		 */
		// 获取用户
		fetchData(pageNum = this.paginationConfig.page, pageSize = this.paginationConfig.pageSize) {
			// 加入page
			this.filterForm.pageNum = pageNum;
			this.filterForm.pageSize = pageSize;
			const params = Object.assign({}, this.filterForm);
			// 清除多余字段
			for (const key in params) {
				if (params[key] === '' || params[key] === 'all') {
					delete params[key];
				}
			}
			if (this.shopId !== -1) {
				params.shopId = this.shopId;
			}
			this.loading = true;
			listUser(params)
				.then(res => {
					if (res.code === 0) {
						this.list = res.data.list;
						this.paginationConfig.total = res.data.total;
						this.paginationConfig.page = res.data.pageNum;
					}
				})
				.finally(() => {
					this.loading = false;
					this.searchLoading = false;
				});
		},

		// 分页sizes改变
		sizesChange(pageSize) {
			this.fetchData();
		},

		// 分页page改变
		pageChange(page) {
			this.fetchData();
		},

		/**
		 * 按钮组
		 */
		// 点击搜索
		searchByKeyword() {
			this.searchLoading = true;
			this.fetchData(1);
		},

		// 新增
		handleAdd() {
			this.$refs.userDialog.openAdd().then(() => {
				this.fetchData();
			});
		},

		// 二维码新增
		handleQrCodeAdd() {
			if (!this.$store.state.wechat.maInfo.DEFAULT.isOnline) {
				this.$alert('商户小程序未正式发布，暂时不可以获取二维码！', '提示', {
					confirmButtonText: '确定',
					center: true,
					type: 'warning',
					callback: action => {}
				});
			} else {
				this.$refs.dialogUserAddQrCode.open();
			}
		},

		// 编辑
		handleEdit(user) {
			this.$refs.userDialog.openEdit(user.id).then(() => {
				this.fetchData();
			});
		},

		// 更多
		// handleCommand(command, data) {
		//   switch (command) {
		//     case 'psw':
		//       this.handleResetPassword(data)
		//       break
		//     case 'del':
		//       this.handleDel(data)
		//       break
		//     case 'promoters':
		//       this.handleQrCode(data)
		//       break
		//   }
		// },

		// 绑定&解除微信
		handleBindWx(user) {
			if (user.wechatOpenid) {
				this.$confirm(`此操作将解除用户${user.name}的微信绑定, 是否继续?`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
					center: true,
					roundButton: true
				}).then(() => {
					unBindWx({ userId: user.id }).then(res => {
						if (user.id === this.userId) {
							this.$store.state.user.wechatOpenid = '';
						}
						user.wechatOpenid = '';
						this.$notify({
							title: '成功',
							message: '解绑微信成功',
							type: 'success',
							duration: 2000,
							offset: 40
						});
					});
				});
			} else {
				this.$refs.dialogBindWx.open(user, 'user').then(() => {
					this.fetchData();
				});
			}
		},

		// 删除
		handleDel(user) {
			this.$confirm(`此操作将永久删除用户${user.name}, 是否继续?`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				center: true,
				roundButton: true
			}).then(() => {
				deleteUser(user.id).then(res => {
					if (res.code === 0) {
						this.fetchData();
						this.$notify({
							title: '成功',
							message: '删除成功',
							type: 'success',
							duration: 2000,
							offset: 40
						});
					} else {
						this.$message.error(res.msg);
					}
				});
			});
		},

		// 修改密码
		handleResetPassword(user) {
			if (this.businessInfo.syncTmpMerchantId) return;
			this.$refs.resetPw.open(user.name, user.id);
		},

		// 推广二维码
		handleQrCode(user) {
			const { mobilePhone } = user;
			if (!mobilePhone) {
				let el = this.$message({
					showClose: true,
					message: '请先补充员工手机号',
					type: 'warning',
					duration: 5000
				}).$el;
				if (el) el.style.cssText = 'z-index: 3000';
				this.handleEdit(user);
				return;
			}
			if (!this.$store.state.wechat.maInfo.DEFAULT.isOnline) {
				this.$alert('商户小程序未正式发布，暂时不可以获取二维码！', '提示', {
					confirmButtonText: '确定',
					center: true,
					type: 'warning',
					callback: action => {}
				});
			} else {
				this.$refs.dialogUserQrCode.open(user);
			}
		},

		// 打开员工审批
		handleApprove() {
			this.$emit('changeShowType');
		},

		/**
		 * 方法
		 */
		// 格式化角色名
		toRolesName(roles) {
			if (!roles) return '';
			const rolesNames = [];
			for (let i = 0; i < roles.length; i++) {
				rolesNames.push(roles[i].name);
			}
			return rolesNames.join(',');
		}
	}
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.top {
	margin-bottom: 10px;
	.title {
		font-size: 18px;
		font-weight: bold;
	}
}

/* 搜索*/
.list-search {
	padding-top: 10px;
	margin-bottom: 10px;
	.el-select {
		width: 120px;
	}
	.el-input {
		width: 400px;
		margin-right: 10px;
	}
}
</style>
